package com.dylan.历史.guava;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.primitives.Ints;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author : ankang
 * @date : 2020/3/7 22:54
 * @Description :
 */
public class Joiner_Splitter {
    @Test
    public void testJoiner() {
        List<Integer> list1 = Ints.asList(1, 2, 3, 4);
        String str1 = Joiner.on(",").join(list1);
        System.out.println(str1); // 1,2,3,4

        List<String> list2 = Stream.of("a", null, "b").collect(Collectors.toList());
//        String str2 = Joiner.on(",").join(list2);
//        System.out.println(str2); // 空指针，不能有null

        String str3 = Stream.of("a", null, "b").collect(Collectors.joining(","));
        System.out.println(str3); // a,null,b

        String str4 = String.join(",", list2);
        System.out.println(str4); // a,null,b

        String str5 = StringUtils.join(list2, ",");
        System.out.println(str5); // a,,b
    }

    @Test
    public void testSplitter() {
        String str = ",a, , b , c ";
        String[] arr1 = str.split(",");
        printArray(arr1); // __a_ _ b _ c _

        String[] arr2 = StringUtils.split(str, ",");
        printArray(arr2); // _a_ _ b _ c _

        printArray(Splitter.on(",").splitToList(str)); // __a_ _ b _ c _
        printArray(Splitter.on(",").trimResults().splitToList(str)); // __a__b_c_
        // 去除空字符串、并且每个元素去除左右空格
        printArray(Splitter.on(",").omitEmptyStrings().trimResults().splitToList(str)); // _a_b_c_
    }


    private void printArray(String[] arr) {
        for (String s : arr) {
            System.out.print("_" + s);
        }
        System.out.println("_");
    }
    private void printArray(List<String> arr) {
        for (String s : arr) {
            System.out.print("_" + s);
        }
        System.out.println("_");
    }
}
